package com.shadt.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shadt.cloud.dao.BranchChannelDao;
import com.shadt.cloud.dao.BranchDao;
import com.shadt.cloud.dao.ChannelDao;
import com.shadt.cloud.dao.UserDao;
import com.shadt.cloud.entity.CloudBranch;
import com.shadt.cloud.entity.CloudBranchChannel;
import com.shadt.cloud.entity.User;
import com.shadt.cloud.service.AdminService;
import com.shadt.cloud.vo.BranchChannelVo;
import com.shadt.cloud.vo.BranchVo;
import com.shadt.cloud.vo.ChannelVo;
import com.shadt.core.util.MD5Util;

/**
 * 后台业务逻辑层实现类	
 * @author SongR
 *
 */
@Service
public class AdminServiceImpl implements AdminService{
	
	@Autowired
	UserDao uDao;
	
	@Autowired
	BranchDao bDao;

	@Autowired
	ChannelDao cDao;
	
	@Autowired
	BranchChannelDao bcDao;
	
	/**
	 * 用户登录
	 */
	public User login(User user) throws Exception {
		User u = uDao.getR(user.getName()+user.getPassword());
		if(null==u){
			String hql = "from User where (username=:name or phone=:phone) and password=:password";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", user.getName());
			params.put("phone", user.getName());
			params.put("password", MD5Util.md5(user.getPassword()));
			u = uDao.get(hql,params);
			if(null!=u){
				uDao.addR(user.getName()+u.getPassword(), u);
			}
		}
		return u;
	}
	
	/**
	 * 实现退出登录
	 */
	public boolean logout(User u) throws Exception {
		uDao.deleteR(u.getUsername()+u.getPassword());
		uDao.deleteR(u.getPhone()+u.getPassword());
		return false;
	} 
	
	/**
	 * 实现验证平台名称是否存在
	 */
	public boolean checkName(String name) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", name);
		CloudBranch branch = bDao.get("from CloudBranch where name=:name and status!=-1",params);
		if(null==branch){
			return true;
		}
		return false;
	}

	/**
	 * 实现用户注册
	 */
	public User register(User user) throws Exception {
		user.setPassword(MD5Util.md5(user.getPassword()));
		user.setCreateTime(new Date());
		user.setType(1);
		user.setState(0);
		uDao.save(user);
		return user;
	}

	/**
	 * 实现获取所有栏目
	 */
	@SuppressWarnings("rawtypes")
	public List<ChannelVo> getParentChannel(String sSearch, int iDisplayStart, int iDisplayLength) throws Exception {
		String sql = "select * from community_channel where isenable = 1 and parentseq is null ";
		if(!sSearch.equals("")&&sSearch!=null){
			sql+=" and (title like '%"+sSearch.trim()+"%' or channelKey like '%"+sSearch.trim()+"%') ";
		}
		sql+=" order by sortno limit "+ iDisplayStart + "," + iDisplayLength;
		List l = cDao.getBySql(sql);
		Iterator it = l.iterator();
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			ChannelVo vo = new ChannelVo();
			vo.setId(m.get("seq").toString());
			vo.setName(m.get("title").toString());
			vo.setKey(m.get("channelkey").toString());
			vos.add(vo);
		}
		return vos;
	}
	/**
	 * 实现获取所有栏目
	 */
	@SuppressWarnings("rawtypes")
	public List<ChannelVo> getParentChannel() throws Exception {
		String sql = "select * from community_channel where isenable = 1 and parentseq is null  order by sortno ";
		List l = cDao.getBySql(sql);
		Iterator it = l.iterator();
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			ChannelVo vo = new ChannelVo();
			vo.setId(m.get("seq").toString());
			vo.setName(m.get("title").toString());
			vo.setKey(m.get("channelkey").toString());
			vos.add(vo);
		}
		return vos;
	}
	/**
	 * 实现获取栏目数
	 */
	public String countParentChannel(String sSearch) throws Exception {
		String sql = "select count(1) from community_channel where isenable = 1 and parentseq is null ";
		if(!sSearch.equals("")&&sSearch!=null){
			sql+=" and (title like '%"+sSearch.trim()+"%' or channelKey like '%"+sSearch.trim()+"%') ";
		}
		String s = cDao.countSql(sql);
		return s;
	}

	/**
	 * 实现获取子栏目
	 */
	@SuppressWarnings("rawtypes")
	public List<ChannelVo> getChildChannel(String sSearch, int iDisplayStart, int iDisplayLength, String id, Long bid)
			throws Exception {
		String sql = "select * from community_channel where isenable = 1 and parentseq =" + id;
		if(!sSearch.equals("")&&sSearch!=null){
			sql+=" and (title like '%"+sSearch.trim()+"%' or channelKey like '%"+sSearch.trim()+"%') ";
		}
		sql+=" order by sortno limit "+ iDisplayStart + "," + iDisplayLength;
		List<CloudBranchChannel> bc = bcDao.find("from CloudBranchChannel where branchid='"+bid +"' and status!=-1");
		CloudBranch branch = bDao.get(CloudBranch.class,bid);
		List l = cDao.getBySql(sql);
		Iterator it = l.iterator();
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			ChannelVo vo = new ChannelVo();
			if(null!=branch){
				if(bc.size()>0){
					for (CloudBranchChannel v : bc) {
						if(m.get("channelkey").toString().equals(v.getKey())){
							if(v.getStatus()==0){
								vo.setState(0);
							}else if(v.getStatus()==1){
								vo.setState(1);
							}else if(v.getStatus()==2){
								vo.setState(2);
							}else if(v.getStatus()==3){
								vo.setState(3);
							}
						}
					}
				}else{
					vo.setState(-1);
				}
			}else{
				vo.setState(9);//暂无可用平台
			}
			vo.setId(m.get("seq").toString());
			vo.setName(m.get("title").toString());
			vo.setKey(m.get("channelkey").toString());
			vos.add(vo);
		}
		return vos;
	}

	/**
	 * 实现获取子栏目数
	 */
	public String countChildChannel(String sSearch, String id) throws Exception {
		String sql = "select count(1) from community_channel where isenable = 1 and parentseq =" + id;
		if(!sSearch.equals("")&&sSearch!=null){
			sql+=" and (title like '%"+sSearch.trim()+"%' or channelKey like '%"+sSearch.trim()+"%') ";
		}
		String s = cDao.countSql(sql);
		return s;
	}

	/**
	 * 实现栏目权限申请
	 */
	public boolean applyChannel(String key, String name, Long id) throws Exception {
		CloudBranchChannel bc = bcDao.get("from CloudBranchChannel where branchid="+id+" and key='"+key+"'");
		if(null==bc){
			bc=new CloudBranchChannel();
			bc.setBranchid(id);
			bc.setCreattime(new Date());
			bc.setKey(key);
			bc.setName(name);
			bc.setStatus(2);
			bcDao.save(bc);
		}else{
			bc.setBranchid(id);
			bc.setCreattime(new Date());
			bc.setKey(key);
			bc.setName(name);
			bc.setStatus(2);
			bcDao.update(bc);
		}
		return true;
	}

	/**
	 * 实现取消权限申请
	 */
	public boolean cancelApplyChannel(String key, Long id) throws Exception {
		CloudBranchChannel bc = bcDao.get("from CloudBranchChannel where branchid="+id+" and key='"+key+"'");
		if(bc.getStatus()==1){
			bc.setStatus(-1);
			bcDao.update(bc);
			return true;
		}
		return false;
	}

	/**
	 * 实现暂停权限申请
	 */
	public boolean stopApplyChannel(String key, Long id) throws Exception {
		CloudBranchChannel bc = bcDao.get("from CloudBranchChannel where branchid="+id+" and key='"+key+"'");
		if(bc.getStatus()==0){
			bc.setStatus(2);
			bcDao.update(bc);
			return true;
		}
		return false;
	}

	/**
	 * 实现恢复权限
	 */
	public boolean recoveryApplyChannel(String key, Long id) throws Exception {
		CloudBranchChannel bc = bcDao.get("from CloudBranchChannel where branchid="+id+" and key='"+key+"'");
		if(bc.getStatus()==2){
			bc.setStatus(0);
			bcDao.update(bc);
			return true;
		}else{
			return false;
		}
	}

	@SuppressWarnings("rawtypes")
	public List<BranchChannelVo> getBranchChannel(String sSearch, int iDisplayStart, int iDisplayLength,User u) throws Exception {
		String sql = "select * from cms_cloud_branch_channel a,cms_cloud_branch b where a.branch_id=b.branch_id  and a.status=2";
		if(!sSearch.equals("")&&sSearch!=null){
			sql+= " and (b.branch_name like '%"+sSearch+"%' or a.channel_key like '%"+sSearch+"%' OR a.channel_name like '%"+sSearch+"%')";
		}
		sql+=" order by a.creattime desc limit "+ iDisplayStart + "," + iDisplayLength;
		List l = bcDao.getBySql(sql);
		Iterator it = l.iterator();
		List<BranchChannelVo> vos = new ArrayList<BranchChannelVo>();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			BranchChannelVo vo = new BranchChannelVo();
			vo.setId(new Long(m.get("id").toString()));
			vo.setKey(m.get("channel_key")!=null?m.get("channel_key").toString():"");
			vo.setName(m.get("channel_name")!=null?m.get("channel_name").toString():"");
			vo.setCreattime(m.get("creattime")!=null?m.get("creattime").toString():"");
			vo.setBranchid(new Long(m.get("branch_id").toString()));
			vo.setBranchname(m.get("branch_name")!=null?m.get("branch_name").toString():"");
			vo.setStarttime(m.get("starttime")!=null?m.get("starttime").toString():"");
			vo.setEndtime(m.get("endtime")!=null?m.get("endtime").toString():"");
			vo.setState(Integer.parseInt(m.get("status").toString()));
			vos.add(vo);
		}
		return vos;
	}

	@Override
	public Object countBranchChannel(String sSearch,User u) throws Exception {
		String sql = "select count(1) from cms_cloud_branch_channel a,cms_cloud_branch b where a.branch_id=b.branch_id  and a.status!=-1";
		if(!sSearch.equals("")&&sSearch!=null){
			sql+= " and (b.branch_name like '%"+sSearch+"%' or a.channel_key like '%"+sSearch+"%' OR a.channel_name like '%"+sSearch+"%')";
		}
		String s = cDao.countSql(sql);
		return s;
	}

	/**
	 * 实现根据用户获取商户列表
	 */
	public List<BranchVo> getBranch(Long id,Integer type) throws Exception {
		String hql = "from CloudBranch where status=0";
		if(type==1){
			hql+="and userId="+id;
		}
		List<CloudBranch> cbs = bDao.find(hql);
		List<BranchVo> vos = new ArrayList<BranchVo> ();
		for (CloudBranch b : cbs) {
			BranchVo vo = new BranchVo();
			BeanUtils.copyProperties(b, vo);
			vos.add(vo);
		}
		return vos;
	}

	@Override
	public void setState(Long id, int i) throws Exception {
		CloudBranchChannel bc = bcDao.get(CloudBranchChannel.class, id);
		bc.setStatus(i);
		bcDao.update(bc);
	}

	public void setChannelState(String key, Long long1, int i) throws Exception {
		String hql = "from CloudBranchChannel where key=:key and branchid=:branchid";
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("key", key);
		m.put("branchid", long1);
		CloudBranchChannel bc = bcDao.get(hql,m);
		bc.setStatus(i);
		bcDao.update(bc);
	}

}
